package com.wlz.splitpackage.customlength;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 *  自定义消息 解码器
 * @author wlz
 * @date 2022-07-09  3:45 下午
 */
@Slf4j
public class MyMessageDecoder extends ByteToMessageDecoder {

    int length = 0;

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List<Object> out) throws Exception {

      log.info("MyMessageDecoder decoder 被调用");
      log.info("ByteBuf : {}", in);

      if (in.readableBytes() >= 4) {
          if (length == 0) {
              length = in.readInt();
          }
          if (in.readableBytes() < length) {
              log.info(" 当前可读数据不够，继续等待....");
              return;
          }
          byte[] content = new byte[length];
          if (in.readableBytes() >= length) {
              in.readBytes(content);

              // 封装成 MyMessageProtocol 对象，传递到下一个 handler 业务处理
              MyMessageProtocol myMessageProtocol = new MyMessageProtocol();
              myMessageProtocol.setLen(length);
              myMessageProtocol.setContent(content);
              out.add(myMessageProtocol);
          }
          length = 0;
      }

    }
}
